package com.itzdm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzdm.reggie.common.constant.MessageConstant;
import com.itzdm.reggie.common.exception.DeletionNotAllowedException;
import com.itzdm.reggie.entity.Category;
import com.itzdm.reggie.entity.Dish;
import com.itzdm.reggie.entity.Setmeal;
import com.itzdm.reggie.mapper.CategoryMapper;
import com.itzdm.reggie.service.CategoryService;
import com.itzdm.reggie.service.DishService;
import com.itzdm.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 分页查询分类
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page pageCate(int page, int pageSize) {
        //添加分页条件
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        wrapper.orderByAsc(Category::getSort);

        Page p = page(pageInfo, wrapper);
        return p;
    }

    /**
     * 删除分类
     * @param ids
     */
    @Override
    public void removeCateById(Long ids) {
        //查询当前分类是否关联了菜品
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId, ids);
        long countDish = dishService.count(dishWrapper);

        if (countDish > 0) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //查询当前分类是否关联了套餐
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, ids);
        long countSetmeal = setmealService.count(setmealWrapper);
        if (countSetmeal > 0) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        super.removeById(ids);

    }


    /**
     * 根据条件查询分类
     * @param category
     * @return
     */
    @Override
    public List<Category> listCates(Category category) {
        //条件构造
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        //进行排序条件
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        return list(wrapper);
    }
}
